import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../bean/bean_train.dart';
import '../../bean/bean_user.dart';
import '../../common/user_helper.dart';
import '../../face/face_detector_view.dart';
import '../../net/dio_utils.dart';
import '../../utils/toast_utils.dart';

class TrainLineCourseDetailsController extends GetxController {
  int trainId;

  TrainLineCourseDetailsController(this.trainId);

  CancelToken _cancelToken;
  TrainBean _trainBean;

  CancelToken _userJoinTrainToken;
  UserTrainStudyEntity _userJoinTrainBean;

  TrainBean get trainBean => _trainBean;

  requestTrainDetails({bool click = false, bool loading = true}) async {
    _isLoading = loading;
    if (click) {
      update(["root"]);
    }

    String userAddress = UserHelper.getInstance.userAddress;
    num userLongitude = UserHelper.getInstance.userLongitude;
    num userLatitude = UserHelper.getInstance.userLatitude;

    Map<String, dynamic> monthMap = {
      "trainId": trainId,
    };
    if (_cancelToken != null && !_cancelToken.isCancelled) {
      _cancelToken.cancel();
    }
    _cancelToken = new CancelToken();
    //获取培训的信息
    ResponseInfo statisRresponseInfo = await DioUtils.instance.postRequest(
      url: HttpHelper.trainDetailsInfo,
      jsonMap: monthMap,
      encrypt: true,
      cancelTag: _cancelToken,
    );
    _isLoading = false;
    if (statisRresponseInfo.success) {
      if (statisRresponseInfo.data != null) {
        _trainBean = TrainBean.fromJson(statisRresponseInfo.data);
      }
    } else {
      _trainBean = null;
    }

    /// 获取是否参与培训
    await querySelectTrain(trainId);
    update(["root"]);
  }

  ///查询是否参与了此培训
  Future<bool> querySelectTrain(int trainId) async {
    UserBean userBean = UserHelper.getInstance.userBean;
    if (_userJoinTrainToken != null && !_userJoinTrainToken.isCancelled) {
      _userJoinTrainToken.cancel();
    }
    _userJoinTrainToken = new CancelToken();
    //查询用户是否参与培训
    ResponseInfo statisRresponseInfo = await DioUtils.instance.postRequest(
        url: HttpHelper.selectUserLineTrainDetailsUrl,
        cancelTag: _userJoinTrainToken,
        encrypt: true,
        jsonMap: {
          "trainId": trainId,
        });
    if (statisRresponseInfo.success) {
      var data = statisRresponseInfo.data;
      if (data != null) {
        _userJoinTrainBean = UserTrainStudyEntity.fromJson(data);
        return true;
      }
    }
    return false;
  }

  bool _isLoading = true;

  bool getIsLoading() {
    return _isLoading;
  }

  UserTrainStudyEntity get userJoinTrainBean => _userJoinTrainBean;

  CancelToken _userJoinToTrainToken;

  ///立即加入培训
  void requestJoinTrain({String faceImageUrl}) async {
    debugPrint("加入培训 faceImageUrl:$faceImageUrl");
    _isLoading = true;
    update(["root"]);

    if (_userJoinToTrainToken != null && !_userJoinToTrainToken.isCancelled) {
      _userJoinToTrainToken.cancel();
    }
    ResponseInfo statisRresponseInfo = await DioUtils.instance.postRequest(
        url: HttpHelper.selectUserTrainAddsUrl,
        cancelTag: _userJoinToTrainToken,
        encrypt: true,
        jsonMap: {
          "trainId": trainId,
          "faceImageUrl": faceImageUrl ?? "",
        });
    if (statisRresponseInfo.success) {
      var data = statisRresponseInfo.data;
    } else {
      String message = statisRresponseInfo.message;
      if (message.contains("开启人脸识别")) {
        showOpenFaceTipe();
        _isLoading = false;
        update(["root"]);

        return;
      }
      ToastUtils.showToast(statisRresponseInfo.message);
    }
    await requestTrainDetails();
  }

  bool signLoading = false;

  void requestTrainOff({int autoFinishNoSign = 0}) async {
    signLoading = true;
    update(["signOnOffId"]);

    if (_userJoinToTrainToken != null && !_userJoinToTrainToken.isCancelled) {
      _userJoinToTrainToken.cancel();
    }
    ResponseInfo statisRresponseInfo = await DioUtils.instance.postRequest(
        url: HttpHelper.selectUserTrainSignOffUrl,
        cancelTag: _userJoinToTrainToken,
        encrypt: true,
        jsonMap: {"trainId": trainId, "autoFinishNoSign": autoFinishNoSign});
    signLoading = false;
    if (statisRresponseInfo.success) {
      var data = statisRresponseInfo.data;
      await requestTrainDetails();
    } else {
      if (statisRresponseInfo.code == 202) {
        dynamic result = await Get.defaultDialog(
            title: "提示",
            content: Text("${statisRresponseInfo.message}"),
            textCancel: "取消",
            textConfirm: "确认",
            onConfirm: () {
              Get.back(result: true);
            });
        if (result != null && result) {
          requestTrainOff(autoFinishNoSign: 1);
        } else {
          update(["signOnOffId"]);
        }
      } else {
        Get.defaultDialog(
            title: "操作失败",
            content: Text(statisRresponseInfo.message ?? "网络请求错误"),
            textCancel: "关闭");
        update(["signOnOffId"]);
      }
    }
  }

  bool checkFinishLoading = false;

  ///检查一下是否完成了培训
  Future<bool> checkFinishTrainRequest({bool click = false}) async {
    checkFinishLoading = true;
    if (click) {
      update(["checkFinishId"]);
    }
    ResponseInfo statisRresponseInfo = await DioUtils.instance.postRequest(
        url: HttpHelper.sUserTrainFinishCheckUrl,
        cancelTag: _userJoinToTrainToken,
        encrypt: true,
        jsonMap: {
          "trainId": trainId,
        });
    checkFinishLoading = false;
    if (statisRresponseInfo.success) {
      update(["root", "checkFinishId"]);
      return true;
    } else {
      update(["checkFinishId"]);
      return false;
    }
  }

  void showOpenFaceTipe() async {
    dynamic result = await Get.defaultDialog(
        title: "提示",
        content: Text("本培训需要人脸识别认证后参与培训"),
        textCancel: "取消",
        textConfirm: "去认证",
        onConfirm: () {
          Get.back(result: true);
        });
    if (result != null && result) {
      dynamic faceResult = await Get.to(() => FaceDetectorView(
            key: UniqueKey(),
          ));
      if (faceResult != null && faceResult.toString().isNotEmpty) {
        requestJoinTrain(faceImageUrl: faceResult);
      }
    }
  }
}
